"""
Configuration Management

雷达客户端配置管理
"""

import json
from typing import Dict, Any, Optional
from pathlib import Path


class RadarConfig:
    """雷达配置类"""

    # 默认RJ45配置
    DEFAULT_RJ45_CONFIG = {
        "ip_address": "192.168.1.100",
        "subnet_mask": "255.255.255.0",
        "gateway": "192.168.1.1",
        "data_port": 50001,
        "control_port": 50002,
        "timeout": 1000,
        "retry_count": 3,
        "heartbeat_interval": 5000
    }

    # 默认RS232配置
    DEFAULT_RS232_CONFIG = {
        "port": "COM1",
        "baud_rate": 115200,
        "data_bits": 8,
        "stop_bits": 1,
        "parity": "none",
        "flow_control": "none",
        "timeout": 100,
        "response_delay": 50,
        "max_retries": 3
    }

    # 默认通用配置
    DEFAULT_GENERAL_CONFIG = {
        "enable_logging": True,
        "log_level": "INFO",
        "auto_reconnect": True,
        "reconnect_interval": 3000,
        "data_callback_enabled": True,
        "command_timeout": 2000
    }

    def __init__(self, config_file: Optional[str] = None):
        """
        初始化配置

        Args:
            config_file: 配置文件路径
        """
        self.config_file = config_file
        self.config = self._load_config()

    def _load_config(self) -> Dict[str, Any]:
        """加载配置"""
        if self.config_file and Path(self.config_file).exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            except (json.JSONDecodeError, IOError) as e:
                print(f"加载配置文件失败: {e}")
                return self._get_default_config()
        else:
            return self._get_default_config()

    def _get_default_config(self) -> Dict[str, Any]:
        """获取默认配置"""
        return {
            "rj45": self.DEFAULT_RJ45_CONFIG,
            "rs232": self.DEFAULT_RS232_CONFIG,
            "general": self.DEFAULT_GENERAL_CONFIG
        }

    def get_rj45_config(self) -> Dict[str, Any]:
        """获取RJ45配置"""
        return self.config.get('rj45', self.DEFAULT_RJ45_CONFIG)

    def get_rs232_config(self) -> Dict[str, Any]:
        """获取RS232配置"""
        return self.config.get('rs232', self.DEFAULT_RS232_CONFIG)

    def get_general_config(self) -> Dict[str, Any]:
        """获取通用配置"""
        return self.config.get('general', self.DEFAULT_GENERAL_CONFIG)

    def save_config(self, config_file: Optional[str] = None) -> None:
        """保存配置到文件"""
        if config_file:
            self.config_file = config_file

        if self.config_file:
            try:
                with open(self.config_file, 'w', encoding='utf-8') as f:
                    json.dump(self.config, f, indent=2, ensure_ascii=False)
            except IOError as e:
                print(f"保存配置文件失败: {e}")

    def update_config(self, section: str, key: str, value: Any) -> None:
        """更新配置项"""
        if section not in self.config:
            self.config[section] = {}
        self.config[section][key] = value

    def get_config(self, section: str, key: str, default: Any = None) -> Any:
        """获取配置项"""
        return self.config.get(section, {}).get(key, default)

    @staticmethod
    def create_sample_config(file_path: str) -> None:
        """创建示例配置文件"""
        sample_config = {
            "rj45": RadarConfig.DEFAULT_RJ45_CONFIG,
            "rs232": RadarConfig.DEFAULT_RS232_CONFIG,
            "general": RadarConfig.DEFAULT_GENERAL_CONFIG,
            "comments": {
                "rj45": "RJ45网络接口配置",
                "rs232": "RS232串口接口配置",
                "general": "通用配置选项"
            }
        }

        try:
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(sample_config, f, indent=2, ensure_ascii=False)
            print(f"示例配置文件已创建: {file_path}")
        except IOError as e:
            print(f"创建示例配置文件失败: {e}")